<?php

/*============================================
Classe Instrument
============================================*/

class Instrument extends ModelObject{

	protected static $cached_object_list= array();
	protected $nom;
	protected $categorie;

	protected function __construct( $nom,$categorie){
		try{
			
			$this->nom = $nom;
			$this->categorie = $categorie;
		}
		catch(Excpetion $e){
			throw new Exception("La construction de l'objet de type get_class($this) a échouée",0,$e);
		}
	}

	public function getNom(){
		return $this->nom;
	}

	public function getCategorie(){
		return Instrument::get($this->categorie);
	}

	public function setNom( $nom){
		try{
			$temp = $this->nom;
			if($this->nom !== $nom){
				$this->nom = $nom;
				$this->update();
			}
		}
		catch(Exception $e){
			$this->nom = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setNom() a échouée",0,$e);
		}
	}

	public function setCategorie( $categorie){
		try{
			$temp = $this->categorie;
			if(is_null($categorie)){
				if($this->categorie !== $categorie){
					$this->categorie = null;
					$this->update();
				}
			}
			else if(!($categorie instanceof Instrument) || is_null($categorie->getId())){
				throw new Exception("Le paramètre \$categorie de type get_class($categorie) n'est pas du bon type ou n'est pas présent dans la base");
			}
			else {
				if($this->categorie !== $categorie->getId()){
					$this->categorie = $categorie->getId();
					$this->update();
				}
			}
		}
		catch(Exception $e){
			$this->categorie = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setCategorie() a échouée",0,$e);
		}
	}

	public static function create( $nom,$categorie){
		try{
			$instrument = new Instrument($nom, $categorie);
			$instrument->insert();
			Instrument::cacheObject($instrument);
			return $instrument;
		}
		catch(Excpetion $e){
			throw new Exception("La création de l'objet de type Instrument a échouée",0,$e);
		}
	}

	public static function get( $instrument){
		$dbh = SingletonPDO::getInstance();
		try{
			if(is_null($instrument) || $instrument === "") {
				return null;
			}
			if(Instrument::existsInCache($instrument)) {
				return Instrument::getFromCache($instrument);
			}
			$dbh->beginTransaction();
			$sql= 'SELECT * FROM `instrument` WHERE `instrument` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$instrument));
			if ($row = $stmt->fetch()){
				$instrument = new Instrument( $row['nom'],$row['categorie']);
				$instrument->id =  $row['instrument'];
				$dbh->commit();
				Instrument::cacheObject($instrument);
				return $instrument;
			}
			else {
				$dbh->commit();
				return null;
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récupération de l'objet ayant l'id ". $instrument . " a échouée",0,$e);
		}
	}

	protected function update(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql='UPDATE `instrument` SET `nom` = :nom, `categorie` = :categorie WHERE `instrument` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':nom'=>$this->nom, ':categorie'=>$this->categorie, ':id'=>$this->id));
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La modification de l'objet de type ".get_class($this)." ayant l'id ". $this->id . " a échouée",0,$e);
		}
	}

	public function delete(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql = 'DELETE FROM `instrument` WHERE `instrument` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$this->id));
			Instrument::removeObjectFromCache($this->id);
			$this->id = null;
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de l'objet de type ".get_class($this)." ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	protected function insert(){
		$dbh = SingletonPDO::getInstance();
		try{
			if (is_null($this->id)) {
				$dbh->beginTransaction();
				$sql='INSERT INTO `instrument` ( `nom`, `categorie`) VALUES (:nom, :categorie)';
				$stmt = $dbh->prepare($sql);
				$stmt->execute(array(':nom'=>$this->nom, ':categorie'=>$this->categorie));
				$this->id = $dbh->lastInsertId();
				$dbh->commit();
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("L'insertion de l'objet de type ".get_class($this)." a échouée",0,$e);
		}
	}

	public static function getAll( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql = 'SELECT * FROM `instrument`';
			$sql .= self::generateWhereClause($search_params);
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = null;
				if(Instrument::existsInCache($row['instrument'])){
					$obj = Instrument::getFromCache($row['instrument']);
				}
				else{
					$obj = new Instrument( $row['nom'],$row['categorie']);
				}
				if(!is_null($obj)){
					$obj->id = $row['instrument'];
					Instrument::cacheObject($obj);
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récuperation de la liste d'objets de type Instrument a échouée",0,$e);
		}
	}

	public static function deleteAll( $search_params = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql_delete = 'DELETE FROM `instrument`';
			$sql_select = 'SELECT instrument FROM `instrument`';
			$sql_delete .= self::generateWhereClause($search_params);
			$sql_select .= self::generateWhereClause($search_params);
			$stmt_delete = $dbh->prepare($sql_delete);
			$stmt_select = $dbh->prepare($sql_select);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$var_select = $stmt_select->execute($array);
			$tab_to_delete_objects = $stmt_select->fetchAll();
			if(sizeof($tab_to_delete_objects) > 0){
				$var_delete = $stmt_delete->execute($array);
				foreach($tab_to_delete_objects as $ind => $row){
					$existing_object = Instrument::getObjectFromCache($row['instrument']);
					if(!is_null($existing_object)){
						$existing_object->id = null;
						Instrument::removeObjectFromCache($row['instrument']);
					}
				}
			}
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de la liste d'objets de type Instrument a échouée",0,$e);
		}
	}

	/*fonction de jointure*/
	public function getListCompetence( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$objs = array();
			$sql = 'SELECT `competence` FROM `competence`';
			$where = self::generateWhereClause($search_params);
			if($where === ""){
				$sql .= $where.' WHERE `instrument` = :id';
			}
			else{
				$sql .= $where.' AND `instrument` = :id';
			}
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$array[':id'] = $this->id;
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = Competence::get($row['competence']);
				if(!is_null($obj)){
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La recuperation de la liste d'objets de type Competence liés à l'objet de type Instrument ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	/*fonction de jointure*/
	public function getListUserinstrumentconcert( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$objs = array();
			$sql = 'SELECT `userInstrumentConcert` FROM `userinstrumentconcert`';
			$where = self::generateWhereClause($search_params);
			if($where === ""){
				$sql .= $where.' WHERE `instrument` = :id';
			}
			else{
				$sql .= $where.' AND `instrument` = :id';
			}
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$array[':id'] = $this->id;
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = Userinstrumentconcert::get($row['userInstrumentConcert']);
				if(!is_null($obj)){
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La recuperation de la liste d'objets de type Userinstrumentconcert liés à l'objet de type Instrument ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	/*fonction de jointure*/
	public function getListLigneWhereInstrument( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$objs = array();
			$sql = 'SELECT `id_ligne` FROM `ligne`';
			$where = self::generateWhereClause($search_params);
			if($where === ""){
				$sql .= $where.' WHERE `id_instrument` = :id';
			}
			else{
				$sql .= $where.' AND `id_instrument` = :id';
			}
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$array[':id'] = $this->id;
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = Ligne::get($row['id_ligne']);
				if(!is_null($obj)){
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La recuperation de la liste d'objets de type Ligne liés à l'objet de type Instrument ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

}